import {
  Breadcrumb,
  Button,
  Card,
  Form,
  Input,
  message,
  Radio,
  Space,
  Upload,
} from 'antd'
import { Link } from 'react-router-dom'
import styles from './index.module.scss'
import { PlusOutlined } from '@ant-design/icons'
import ReactQuill from 'react-quill'
import 'react-quill/dist/quill.snow.css'
import Channel from '@/components/Channel'
import { useEffect, useRef, useState } from 'react'
import {
  editContent,
  getContent,
  submitArticles,
} from '@/store/actions/publish'
import { history } from '@/utils/history'
import { useParams } from 'react-router-dom'
import { useDispatch } from 'react-redux'

const Publish = () => {
  const dispatch = useDispatch()
  const params = useParams()
  const isEdit = !!params.id
  useEffect(() => {
    //判断是否是编辑状态
    if (isEdit) {
      dispatch(getContent(params.id)).then((value) => {
        form.setFieldsValue(value)
        form.setFieldValue('type', value.cover.type)
        const newFilelist = value.cover.images.map((item) => ({ url: item }))
        setFileList(newFilelist)
        picRef.current = newFilelist
      })
    }
  }, [])

  const [fileList, setFileList] = useState([])
  const picRef = useRef([])
  const handleChange = ({ fileList }) => {
    const newList = []
    fileList.forEach((item) => {
      if (item.response) {
        console.log(item.response)
        if (item.response.message === 'File too large') {
          return message.warn('图片过大')
        }
        return newList.push({
          url: item.response.data.url,
        })
      }
      newList.push(item)
    })

    setFileList(newList)
    picRef.current = newList
  }

  const [pictureCount, setPictureCount] = useState(1)

  const changePictureCount = (e) => {
    //设置图片数量
    const count = e.target.value
    setPictureCount(count)
    //展示图片
    switch (count) {
      case 0:
        setFileList([])
        return
      case 1:
        setFileList(picRef.current[0] ? [picRef.current[0]] : [])
        return
      case 3:
        setFileList(picRef.current)
    }
  }

  const [form] = Form.useForm()
  const submit = async (msg, isDraft) => {
    const { type, ...rest } = msg

    const data = {
      ...rest,
      cover: {
        type,
        images: fileList.map((item) => item.url),
      },
    }
    if (isEdit) {
      await dispatch(editContent(params.id, data, isDraft))
    } else {
      await dispatch(submitArticles(data, isDraft))
    }
    const successMsg = !isDraft ? '发布成功' : '发布草稿成功'
    message.success(successMsg, 1, () => {
      history.push('/home/article')
    })
  }

  const onFinish = (e) => {
    submit(e, false)
  }

  const submitDraft = () => {
    submit(form.getFieldsValue(), true)
  }

  return (
    <div className={styles.root}>
      <Card
        title={
          <Breadcrumb>
            <Breadcrumb.Item>
              <Link to="/home">首页</Link>
            </Breadcrumb.Item>
            <Breadcrumb.Item>
              {isEdit ? '编辑文章' : '发布文章'}
            </Breadcrumb.Item>
          </Breadcrumb>
        }
        bordered={false}
        style={{
          width: '100%',
        }}
      >
        <Form
          labelCol={{ span: 3 }}
          initialValues={{ type: 1, content: '' }}
          onFinish={onFinish}
          // form={{ form }}
          form={form}
        >
          <Form.Item
            label="标题"
            name="title"
            rules={[{ required: true, message: '请输入文章标题' }]}
          >
            <Input placeholder="请输入文章标题" />
          </Form.Item>

          <Form.Item
            label="频道"
            name="channel_id"
            rules={[{ required: true, message: '请选择文章频道' }]}
          >
            <Channel
              style={{
                width: 400,
              }}
            ></Channel>
          </Form.Item>
          <Form.Item label="封面">
            <Form.Item name="type">
              <Radio.Group onChange={changePictureCount}>
                <Radio value={1}>单图</Radio>
                <Radio value={3}>三图</Radio>
                <Radio value={0}>无图</Radio>
              </Radio.Group>
            </Form.Item>
            {pictureCount === 0 || (
              <Upload
                name="image"
                listType="picture-card"
                className="avatar-uploader"
                showUploadList
                action="http://geek.itheima.net/v1_0/upload"
                fileList={fileList}
                onChange={handleChange}
                multiple={pictureCount === 3}
                maxCount={pictureCount}
              >
                <div style={{ marginTop: 8 }}>
                  <PlusOutlined />
                </div>
              </Upload>
            )}
          </Form.Item>

          <Form.Item
            label="内容"
            name="content"
            rules={[{ required: true, message: '请输入文章内容' }]}
          >
            <ReactQuill
              className="publish-quill"
              theme="snow"
              placeholder="请输入文章内容"
            />
          </Form.Item>

          <Form.Item wrapperCol={{ offset: 3 }}>
            <Space>
              <Button type="primary" htmlType="submit">
                {isEdit ? '编辑文章' : '发布文章'}
              </Button>
              <Button onClick={submitDraft}>存入草稿</Button>
            </Space>
          </Form.Item>
        </Form>
      </Card>
    </div>
  )
}
export default Publish
